package com.lidx.back.statistics.dao.impl;

import com.lidx.back.statistics.dao.ILatestMaterialDao;
import com.lidx.back.statistics.entity.MaterialLatest;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created by Administrator on 2017/4/11.
 */
@Repository
public class LatestMaterialDaoImpl implements ILatestMaterialDao {

    @Autowired
    private SessionFactory sessionFactory;

    public Session getSession() {
        return sessionFactory.getCurrentSession();
    }

    @Override
    public List<MaterialLatest> getLatestMaterials() {
        //StringBuilder sb = new StringBuilder("select from MaterialLatest ml,MaterialPO m");
       /* String sql = "select ml.id,ml.materialId,ml.materialName,m.categoryId,m.categoryOrder" +
                " from MaterialLatest ml,MaterialPO m where ml.materialId = m.id";
        List<Object[]> list = getSession().createQuery(sql).list();
        if(null != list && list.size() > 0){
            for(Object[] o : list){

            }
        }*/
        return getSession().createQuery("from MaterialLatest order by categoryId,categoryOrder").list();
    }

    @Override
    public void saveLatestMaterial(MaterialLatest materialLatest) {
        getSession().save(materialLatest);
        getSession().flush();
    }

    public void deleteLatestMaterial(int id) {
        MaterialLatest ml = (MaterialLatest) getSession().get(MaterialLatest.class,id);
        getSession().delete(ml);
        getSession().flush();
    }

    public void deleteAll() {
        getSession().createQuery("delete from MaterialLatest where 1 = 1").executeUpdate();
        getSession().flush();
    }

    public void saveLatestMaterialList(List<MaterialLatest> materialLatests) {
        for(int i = 0;i<materialLatests.size();i++){
            getSession().save(materialLatests.get(i));
            if((i+1)%20== 0){
                getSession().flush();
                getSession().clear();
            }
        }
    }
}
